import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:meePet/app/Constants.dart';
import 'package:meePet/net/RequestManager.dart';
import 'package:meePet/utils/SPUtil.dart';

import '../bean/TabConfigData.dart';
import '../utils/LogUtils.dart';

class TabConfigManager {
  static TabConfigManager? _instance;

  static TabConfigManager getInstance() {
    _instance ??= TabConfigManager();
    return _instance!;
  }

  static const String found="appear";
  static const String chat="chat";
  static const String fetter="fetter";
  static const String creation="creation";
  static const String mine="mine";

  ///异步获取tab配置，首次即使是默认的也有个极短的异步过程
  Future<String> getConfig() async{
    return _getConfigJson();
  }

  String getConfigLocal(){
    return _getConfigJson(fromNet: false);
  }

  String _getConfigJson({bool fromNet=true}) {
    if(fromNet){
      _getTabConfigNet();
    }
    String dV = SPUtil.load(Constants.keyTabConfig, defaultValue: "");
    if (dV.isEmpty) {
      LogUtils.i("SP获取的是空窜");
      rootBundle.loadString("assets/config.json").then((value) => {
            LogUtils.i("获取的是本地默认tab配置：$value"),
            dV = value,
            LogUtils.i("保存到sp"),
            SPUtil.save(Constants.keyTabConfig, value)
          });
    }
    LogUtils.i("获取的是:$dV");
    return dV;
  }

  void _getTabConfigNet() {
    RequestManager.getClient()
        .getTabs("3.3.0", "fir")
        .then((value) => _dealWithTabData(value));
  }

  void _dealWithTabData(TabConfigData data) {
    if (data.isSuccess()) {
      String netConfig = json.encode(data?.data);
      LogUtils.i("网络获取的tab配置：$netConfig");
      SPUtil.save(Constants.keyTabConfig, netConfig);
      LogUtils.i("网络保存的tab配置：${SPUtil.load(Constants.keyTabConfig)}");
    } else {
      LogUtils.i("请求tab配置错误：${data.code}:${data.msg}");
    }
  }
}
